package logic

import (
	"context"
	"fmt"
	"math/rand"
	"nove/models/cache"
	"nove/models/mysql"

	"nove/noverpc/internal/svc"
	"nove/noverpc/noverpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *noverpc.LoginRequest) (*noverpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	res, _ := cache.RDB.Get(l.ctx, "sendSms"+in.Account).Result()
	if in.SendSms != res {
		return nil, fmt.Errorf("验证码错误，无法修改密码")
	}
	var user mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		user = mysql.User{
			Account:  in.Account,
			Password: in.Password,
			Image:    "1.png",
			NikeName: fmt.Sprintf("用户_%d", rand.Intn(10000)),
		}
		mysql.DB.Debug().Create(&user)
	}
	if in.Password != user.Password {
		return nil, fmt.Errorf("密码错误，请重新输入密码")
	}
	return &noverpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
